var canCompleteCircuit = function (gas, cost) {
  let len = gas.length;
  let space = 0;
  let minSpace = Infinity;
  let minIndex = 0;
  for (let i = 0; i < len; i++) {
    space += gas[i] - cost[i];
    if (space < minSpace) {
      minSpace = space;
      minIndex = i;
    }
  }

  return space < 0 ? -1 : (minIndex + 1) % len;
};

// 优化之后的贪心算法
function canCompleteCircuit(gas, cost) {
  let totalTank = 0;
  let currentTank = 0;
  let startingStation = 0;

  for (let i = 0; i < gas.length; i++) {
    const delta = gas[i] - cost[i];
    totalTank += delta;
    currentTank += delta;

    // 如果当前油箱油量小于0，无法到达下一站
    if (currentTank < 0) {
      // 更新起始站为下一站，并重置当前油箱
      startingStation = i + 1;
      currentTank = 0;
    }
  }

  // 如果总油量足够，则返回起始站，否则返回-1
  return totalTank >= 0 ? startingStation : -1;
}

let gas = [1, 2, 3, 4, 5];
let cost = [3, 4, 5, 1, 2];

console.log(canCompleteCircuit(gas, cost));
